﻿using BLL.Base;
using CommandService;
using Entity;
using Entity.DbEntity;
using Entity.ViewEntity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BLL.Basis
{
    /// <summary>
    /// 绩效价格方法类
    /// </summary>
    public class PieceRateBLL : PubMethod
    {

        Commands cmd;
        LoginInfo userLogin;
        List<OperateModel> OperList;
        OperateModel oper;
        ReturnResult rsl;
        Tools.TxtLogHelper txt;
        public PieceRateBLL()
        {
            cmd = new Commands();
            userLogin = new LoginInfo();
            txt = new Tools.TxtLogHelper();
        }
        /// <summary>
        /// 生产绩效基础数据列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="condition"></param>
        /// <param name="pageCount"></param>
        /// <returns></returns>
        public ReturnResult getPieceRateList(string pageIndex, string pageSize, string condition, ref string pageCount)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(pageIndex))
                {
                    pageIndex = "1";
                }
                if (string.IsNullOrWhiteSpace(pageSize))
                {
                    pageSize = Tools.ConfigReader.Reader["PageSize"];
                }
                StringBuilder sb = new StringBuilder();
                sb.Append("isdel=0 ");
                sb = CreateSelectCondition(sb, condition);

                var list = cmd.PageList<ViewPieceRateInfo>("V_PieceRateInfo", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);
                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 保存计件单价信息
        /// </summary>
        /// <param name="jsonStr">数据字符串</param>
        /// <returns></returns>
        public ReturnResult saveRateData(string jsonStr)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(jsonStr))
                {
                    rsl.Message = "提交数据为空";
                    return rsl;
                }
                var json = JsonConvert.DeserializeObject<JObject>(jsonStr);
                OperList = new List<OperateModel>();
                DbPieceRate rate;
                string type = "";
                if (json["id"].ToString() != "" && json["id"].ToString() != "0")
                {
                    #region 修改操作
                    rate = new DbPieceRate();
                    rate.fitted = json["fitted"].ToString();
                    rate.debug = json["debug"].ToString();
                    rate.test = json["test"].ToString();
                    rate.id = int.Parse(json["id"].ToString());
                    rate.validDate = json["validDate"].ToString();
                    oper = new OperateModel();
                    oper.Data = rate;
                    oper.Types = OperateModel.OperateType.Edit;
                    oper.Conditions = "id";
                    OperList.Add(oper);
                    #endregion
                    type = json["trType"].ToString();
                }
                else
                {
                    var qTable = cmd.GetDataTable("select * from fun_PieceRate_Info where isdel=0");
                  
                    if (string.IsNullOrWhiteSpace(json["proCodes"].ToString()))
                    {
                        #region 未选存货则按存货大类保存数据
                        var arr = json["cCodes"].ToString().Split(',');
                        foreach (string str in arr)
                        {
                            if (!string.IsNullOrWhiteSpace(str))
                            {
                                var dr = qTable.Select("proCode='" + str + "' and trType='type'");
                                if (dr.Length > 0)
                                {
                                    rsl.Message = string.Format("该存货大类已存在计件信息：{0}", str);
                                    return rsl;
                                }
                                rate = new DbPieceRate();
                                rate.fitted = json["fitted"].ToString().Trim();
                                rate.debug = json["debug"].ToString().Trim();
               
                                rate.proCode = str;
                                rate.validDate = json["validDate"].ToString();
                                rate.isDel = 0;
                                rate.status = "Y";
                                rate.dataType = "type";
                                rate.createtime = getNow();
                                rate.createuser = userLogin.UserInfo().userCode;
                                oper = new OperateModel();
                                oper.Data = rate;
                                oper.Types = OperateModel.OperateType.Add;
                                OperList.Add(oper);
                            }

                        }
                        #endregion
                        type = "type";
                    }
                    else
                    {
                        #region 存货计件
                        var arr = json["proCodes"].ToString().Split(',');
                        foreach (string str in arr)
                        {
                            if (!string.IsNullOrWhiteSpace(str))
                            {
                                var dr = qTable.Select("proCode='" + str + "' and trType='pro'");
                                if (dr.Length > 0)
                                {
                                    rsl.Message = string.Format("该存货已存在计件信息：{0}", str);
                                    return rsl;
                                }
                                rate = new DbPieceRate();
                                rate.fitted = json["fitted"].ToString().Trim();
                                rate.debug = json["debug"].ToString().Trim();
                                rate.test = json["test"].ToString();
                                rate.proCode = str;
                                rate.validDate = json["validDate"].ToString();
                                rate.isDel = 0;
                                rate.status = "Y";
                                rate.dataType = "pro";
                                rate.createtime = getNow();
                                rate.createuser = userLogin.UserInfo().userCode;
                                oper = new OperateModel();
                                oper.Data = rate;
                                oper.Types = OperateModel.OperateType.Add;
                                OperList.Add(oper);
                            }

                        }
                        #endregion
                        type = "pro";
                    }
                   
                }
            
                if (OperList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(OperList);
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
      
        /// <summary>
        /// 根据条码查询绩效单价
        /// </summary>
        /// <param name="barCode">条码编码</param>
        /// <param name="pType">组装价格1，调试价格2，检验价格3</param>
        /// <returns></returns>
        public string getBarProductPrice(string barCode,string pType)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from fun_Inventory_Info where ");
                sb.Append("proCode in(select proCode from bar_ProductBarCode_info");
                sb.Append(" where barCode='" + barCode + "') and isdel=0");
                var proTable = cmd.GetDataTable(sb.ToString());
                string proCode = proTable.Rows[0]["proCode"].ToString();
                string proType = proTable.Rows[0]["typeCode"].ToString();
     
                #region 单品价格优先
                sb.Clear();
                sb.Append("select top 1 * from fun_PieceRate_Info where ");
                sb.Append("isdel=0 and status='Y' and proCode='" + proCode + "'");
                var pTable = cmd.GetDataTable(sb.ToString() + " and trType='pro'");
                if (pTable.Rows.Count >0)
                {
                    if (pTable.Rows[0]["validDate"] != null && !string.IsNullOrWhiteSpace(pTable.Rows[0]["validDate"].ToString()))
                    {
                        string date = pTable.Rows[0]["validDate"].ToString();
                        if (DateTime.Parse(date).Date >= DateTime.Now.Date)
                        {
                            if (pType == "0")
                            {
                                return pTable.Rows[0]["fitted"].ToString();//组装单价
                            }
                            else if (pType == "1")
                            {
                                return pTable.Rows[0]["debug"].ToString();//调试单价
                            }
                            else if (pType == "2")
                            {
                                return pTable.Rows[0]["test"].ToString();//检验单价
                            }
                        }
                        else
                        {
                            return "0";
                        }
                    }
                }
                #endregion

                #region 类单价次之
                sb.Clear();
                sb.Append("select top 1 * from fun_PieceRate_Info where ");
                sb.Append("isdel=0 and status='Y' and proCode='" + proType + "'");
                pTable = cmd.GetDataTable(sb.ToString() + " and trType='type'");
                if (pTable.Rows.Count > 0)
                {
                    if (pTable.Rows[0]["validDate"] != null && !string.IsNullOrWhiteSpace(pTable.Rows[0]["validDate"].ToString()))
                    {
                        string date = pTable.Rows[0]["validDate"].ToString();
                        if (DateTime.Parse(date).Date >= DateTime.Now.Date)
                        {
                            if (pType == "0")
                            {
                                return pTable.Rows[0]["fitted"].ToString();//组装单价
                            }
                            else if (pType == "1")
                            {
                                return pTable.Rows[0]["debug"].ToString();//调试单价
                            }
                            else if (pType == "2")
                            {
                                return pTable.Rows[0]["test"].ToString();//检验单价
                            }
                        }
                        else
                        {
                            return "0";
                        }
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                txt.AddLogMsg("方法程序异常(getBarProductPrice)："+ex.Message);
            }
            return "0";
        }
        /// <summary>
        /// 根据id获取价格信息
        /// </summary>
        /// <param name="dataId"></param>
        /// <returns></returns>
        public ReturnResult getProductPriceById(string dataId)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from V_PieceRateInfo where ");
                sb.Append(" id="+dataId);
                rsl.Data = cmd.TableToDictionary(cmd.GetDataTable(sb.ToString()));
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 删除绩效基础数据
        /// </summary>
        /// <param name="dataId">数据id</param>
        /// <returns></returns>
        public ReturnResult DelProductPriceById(string dataId)
        {
            rsl = new ReturnResult();
            try
            {
                DbPieceRate rate = new DbPieceRate();
                rate.id = int.Parse(dataId);
                rate.isDel = 1;
                rate.delDate = getNow();
                rate.delUser = userLogin.UserInfo().userCode;
                OperateModel oper = new OperateModel();
                oper.Data = rate;
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "id";
                rsl = cmd.Edit(oper);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
    }
}
